package pers.vic.upload.utils;

import org.springframework.web.socket.WebSocketSession;
import pers.vic.upload.constant.SessionAttr;
import pers.vic.upload.login.model.User;

import javax.servlet.http.HttpServletRequest;

/**
 * 描述:
 * @author Vic.xu
 * @date 2022-07-07 9:29
 */
public class SessionHelper {

    /**
     * 把当前用户信息放在ThreadLocal 中
     */
    private static final ThreadLocal<User> SOCKET_USER_THREAD_LOCAL = new ThreadLocal<>();

    /**
     * 用户信息存储到session中
     * @param request request
     * @param user user
     */
    public static void storageSessionUser(HttpServletRequest request, User user) {
        request.getSession(true).setAttribute(SessionAttr.SESSION_USER, user);
    }

    /**
     * 获取 WebSocketSession中的用户信息
     */
    public static User getSocketThreadUser(WebSocketSession session) {
        return (User) session.getAttributes().getOrDefault(SessionAttr.SESSION_USER, new User());
    }

    /**
     * 获取 当前线程中的socket的用户信息
     */
    public static User getSocketThreadUser() {
        return SOCKET_USER_THREAD_LOCAL.get();
    }

    /**
     * 移除 当前线程中的socket的用户信息
     */
    public static void removeSocketThreadUser() {
        SOCKET_USER_THREAD_LOCAL.remove();
    }

    public static void setSocketThreadUser(WebSocketSession session) {
        User user = getSocketThreadUser(session);
        SOCKET_USER_THREAD_LOCAL.set(user);
    }

    public static String userId() {
        User sessionUser = getSocketThreadUser();
        if (sessionUser == null) {
            return "-1";
        }
        return sessionUser.getId();
    }

    public static User getSocketThreadUserWithoutNull(){
        User sessionUser = getSocketThreadUser();
        if (sessionUser == null) {
            sessionUser = new User();
            sessionUser.setId("-1");
            sessionUser.setUsername("none");
            sessionUser.setFkOrganizationId("-1");
            sessionUser.setFkOrgCompanyId("-1");
        }
        return sessionUser;
    }


    public static String userName() {
        User sessionUser = getSocketThreadUser();
        if (sessionUser == null) {
            return "none";
        }
        return sessionUser.getUsername();
    }
}
